using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace WebRole1
{
	public class WebRole : RoleEntryPoint
	{
		public override bool OnStart()
		{
			DiagnosticMonitor.Start("DiagnosticsConnectionString");

			// For information on handling configuration changes
			// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
			RoleEnvironment.Changing += RoleEnvironmentChanging;

			CloudStorageAccount.SetConfigurationSettingPublisher(
				(configName, configSetter) => configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));

			CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");

			CloudBlobClient blobClient = account.CreateCloudBlobClient();

			CloudBlobContainer publicContainer = blobClient.GetContainerReference("public");
			CloudBlobContainer privateContainer = blobClient.GetContainerReference("private");

			publicContainer.CreateIfNotExist();
			privateContainer.CreateIfNotExist();

			BlobContainerPermissions publicContainerPermission = publicContainer.GetPermissions();
			publicContainerPermission.PublicAccess = BlobContainerPublicAccessType.Container;
			publicContainer.SetPermissions(publicContainerPermission);

			BlobContainerPermissions privateContainerPermission = privateContainer.GetPermissions();
			privateContainerPermission.PublicAccess = BlobContainerPublicAccessType.Off;
			privateContainer.SetPermissions(privateContainerPermission);

			return base.OnStart();
		}

		private static void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
		{
			// If a configuration setting is changing
			if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
			{
				// Set e.Cancel to true to restart this role instance
				e.Cancel = true;
			}
		}
	}
}